<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="referrer" content="no-referrer" />
    <script src="js/jq.js"></script>
    <script src="js/highcharts.js"></script>
    <link rel="stylesheet" href="styles/index.css">
    <!-- <script src="https://cdn.jsdelivr.net/npm/vue"></script> -->
    
    <!-- <script src="http://cdn.hcharts.cn/highcharts/modules/no-data-to-display.js"></script> -->
</head>
<body>
        <div class="loader">
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
            </div>
        <div id="app">
            <!-- <img class="img" src="../../images/dingbu.jpg" alt="" style="" srcset=""> -->
            <div class="leftContent">
                <div class="header">  
                    <div class="content">
                        <div class="contentTop"> 
                       <!-- <div class="pic"></div> -->
                       <div class="contentRight">
                            <div class="name"></div>
                            <p>回测时间：<span class="startDay"></span>-<span class="endDay"></span></p>
                            <p>初始资金：<span class="startCash"></span></p>
                            <p>累计收益：<span id="pnl" style="color:red;"></span></p>
                        </div>
                    </div>
                        <div class="contentBottom">
                            <div class="contentBottom1"><div class="shouyilv">收益率</div><div>总笔数</div><div>胜率</div><div>最大回撤</div><div>夏普率</div></div> 
                            <div class="contentBottom2"><div id="yield"></div><div id="span3"></div><div id="winning"></div><div id="maxDrawdown"></div><div id="sharperatio"></div></div> 
                           
                        </div>
                    </div>
            </div>
            <!-- <div class="bg"></div> -->
            <div id="container" style="height:500px"></div>
            </div>
            <div class="rightContent">
                <div id="transactionDynamics">
                    <div class="xiangqing1">
                       <ul>
                           <li class="li1">时间</li>
                           <li class="li2">交易</li>
                           <li class="li3">股票名</li>
                           <li class="li4">股价</li>
                           <li class="li5">金额/数量</li>
                           <li class="li6">盈亏金额/收益率</li>
                       </ul>
                    </div>
                    <div class="xiangqing2"></div>
                   </div>
            </div>
  

  
    <!-- <div class="bg"></div> -->
   
      <!-- <div class="radar">
          <div class="radarTxt">开启监控雷达，获取实时调仓提醒</div>
        <div class="btn_fath clearfix" onclick="toogle(this)">
            <div class="move" data-state="off"></div>
            <div class="btnSwitch btn1"></div>
        </div>
      </div>
      <div class="StockPool">
            <div class="radarTxt">股票池：</div>
          <div>
                <img class="rightIcon" src="images/rightIcon.png" alt="" srcset="">
          </div>
        </div> -->
 
        
   

     </div>
     
    <script>
        document.body.parentNode.style.overflowY = "hidden";
$("body").parent().css("overflow-y","hidden");
         $('.img').css('display','none')
$(window).scroll(function(event){//置顶
    if($(window).scrollTop()>700){
        $('.img').css('display','block')
    }else{
        $('.img').css('display','none')
    }
});
$('.img').on('click',function(){
    $("html,body").animate({"scrollTop":0})
})
//股票池按钮
$('.StockPool').on('click',function(){
    if(window.iquant != null && window.iquant.isAndroid()){
	window.iquant.strategyStockListPage(id)
    }else{
        location.href="/backtrader/StockPool?id="+id
    }
  
})
// $(".xiangqing2").on("click","li",function(){ //点击表格跳转app详情
//     if(!$(this).children(".stockCode").text()){
//         alert('请先订阅')
//     }else{
//               // android 跳转股票K线详情
//               if(window.iquant != undefined 
//             && window.iquant.stockKLineDetail instanceof Function){
//             window.iquant.stockKLineDetail($(this).children(".stockCodes").text())
//         }else{
//             location.href="/backtrader/stockKLineDetailIOS?"+$(this).children(".stockCodes").text()
//         }
//     }
      

//         });
        //金额加逗号
            function toThousands(val){
            //金额转换 分->元 保留2位小数 并每隔3位用逗号分开 1,234.56
            var str = (val).toFixed(2) + '';
            var intSum = str.substring(0,str.indexOf(".")).replace( /\B(?=(?:\d{3})+$)/g, ',' );//取到整数部分
            var dot = str.substring(str.length,str.indexOf("."))//取到小数部分搜索
            var ret = intSum + dot;
            return ret;
            }
        //时间
        function ts(ts){
            var date = new Date(ts);
                    Y = date.getFullYear() + '.';
                    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '.';
                    D = (date.getDate()<10?'0'+(date.getDate()):date.getDate()) + ' ';
                    h = date.getHours() + ':';
                    m = date.getMinutes() + ':';
                    s = date.getSeconds(); 
                return (Y+M+D)
        }
        // var url=encodeURI(document.location.toString())
        // var id=url.split('id=')[1].split('&')[0]
        // var token=url.split('id=')[1].split('&')[1].split('token=')[1]
        var id='1068'
        var token='eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyMSIsImlhdCI6MTU1ODUxNDczOCwic3ViIjoie1widXNlcklkXCI6MjF9IiwiZXhwIjoxNTU4NTE2NDY2fQ.FDNZEPQ3LRIxm_y3z5FP64vGuP62a0wVfKFwCR5n4m0'
        var headers={
                'X-Requested-With': 'XMLHttpRequest',
                'Access-Control-Allow-Origin': '*',
                'token':token,
                "Access-Control-Allow-Methods": "POST,GET",
                'Access-Control-Allow-Credentials': true,
                'Access-Control-Expose-Headers': 'FooBar',
                'Content-Type': 'application/json;charset=UTF-8',
                'Accept': 'application/json'
      }
        function toogle(th) {
    var ele = $(th).children(".move");
    if (ele.attr("data-state") == "on") { //雷达监控
        ele.animate({
            left: "0"
        }, 300, function() {
            ele.attr("data-state", "off");
            $.ajax({
               type:"post",    //请求方式
               async:true,    //是否异步
               url:"/api/stock-server/v1/stock/radar/setting",
               dataType :'JSON',
               headers:headers,
             data:JSON.stringify({'enabled':false,'id':id}),
             success:function(){
                if(window.iquant != undefined 
                && window.iquant.strategyRadarSettingChangedAndroid instanceof Function){
                window.iquant.strategyRadarSettingChangedAndroid(id, false)
            }else{
                location.href="/backtrader?id="+id+'&state=false'
            }
             },
             error:function(){
                //  alert('请求失败')
             }
            })
        });
        $(th).removeClass("on").addClass("off");
    } else if (ele.attr("data-state") == "off") {//雷达监控
        ele.animate({
            left: '7vw'
        }, 300, function() {
            $(this).attr("data-state", "on");
            $.ajax({
               type:"post",    //请求方式
               async:true,    //是否异步
               url:"/api/stock-server/v1/stock/radar/setting",
               dataType :'JSON',
               headers:headers,
             data:JSON.stringify({'enabled':true,'id':id}),
             success:function(){
                if(window.iquant != undefined 
                && window.iquant.strategyRadarSettingChangedAndroid instanceof Function){
                window.iquant.strategyRadarSettingChangedAndroid(id, true)
            }else{
                location.href="/backtrader?id="+id+'&state=true'
            }
             }
            })
        });
        $(th).removeClass("off").addClass("on");
    }
}
        var url2=encodeURI(document.location.toString())
        // var sid=url2.split('id=')[1].split('&')[0]
        var sid=1
            var tradeAnalyzer,timeReturnList,recordsList,timeReturnList2
            $.ajax({
                type:"get",    //请求方式
               async:true,    //是否异步
            //    url:"/api/stock-server/v1/stock/strategy/info",
            url:"https://dash.loopbook.cn/api/strategy?sid="+sid,
               dataType :'JSON',
            //    headers: headers,
                 //jsonpCallback:"successCallback",    //自定义跨域参数值，回调函数名也是一样，默认为jQuery自动生成的字符串
            //  data:{
            //      id: id,
                 
            //  },
               success: function(data) {
                   console.log(data.data)
                $(".loader").css('display','none')
                   if(data.status!==0){
                    //    alert(data.msg)
                    //    window.history.go(-1)
                   }
                   if(!data.data.isMine){
                    $('.radar').css('display','none')
                   }else{
                    $('.radar').css('display','block')
                   }
                  if(data.data.name){
                    $(".name").append(data.data.name)
                  }
                  if(data.data.won){
                    $('#winning').append(data.data.won+'%')//胜率
                  }else{
                    $('#winning').append('--')//胜率
                  }
                  if(data.data.startCash){
                    $(".startCash").append(toThousands(data.data.startCash))
                  }
                   
                  $('.startDay').append(ts(data.data.startDay))
                  $('.endDay').append(ts(data.data.endDay))
                //   if(data.data.radarStatus=='-1'){//未开启雷达
                    
                //     $('.btn_fath').addClass('off')
                //     $('.move').attr('data-state','off')
                //   }else{
                //     $('.btn_fath').addClass('on')
                //     $('.move').attr('data-state','on')
                //   }

                   var data=data.data
                   var html1='',html2='',html3='',html4=''
                    if(data.codesCount){
                        for(var i in data.codesCount){
                            if(i=='SZ'){
                                html1='沪深('+data.codesCount[i]+') '   
                            }
                            if(i=='HK'){
                                html2='港股('+data.codesCount[i]+') '
                            }
                            if(i=='US'){
                                html3='美股('+data.codesCount[i]+') '
                            }
                            if(i=='JP'){
                                html4='日股('+data.codesCount[i]+') '
                            }    
                        }
                        $('.StockPool .radarTxt').append(html1+html2+html3+html4)
                    }else{
                        $('.StockPool').css('display','none')
                    }
                   if(data){
                    var annualReturn
                   if(data.annualReturn){
                    annualReturn=Object.entries(data.annualReturn)
                    var annualReturnVal=[]
                    for(var i=0;i<annualReturn.length;i++){
                       
                        annualReturnVal.push(annualReturn[i][1])
                        
                }
                annualReturnVal.sum = function (){//求和
                    var result = 0;
                    for(var i = 0; i < this.length; i++) {
                    result += this[i];
                    }
                    return result;
                    };
                    var yearPnl=(annualReturnVal.sum()/annualReturnVal.length).toFixed(2)
                    $("#yearPnl").append(yearPnl+'%')//年化收益
                   }else{
                    $("#yearPnl").append('--')//年化收益
                   }
                   }
                  
                  if(data.tradeAnalyzer){
                    tradeAnalyzer=data.tradeAnalyzer
                  }
                
                if(tradeAnalyzer.total){
                    $("#span1").append(tradeAnalyzer.total.closed)
                    $("#span2").append(tradeAnalyzer.total.open)
                    $("#span3").append(tradeAnalyzer.total.total)
                }else{
                    $("#span1").append('--')
                    $("#span2").append('--')
                    $("#span3").append('--')
                }
                if(data.sqn){
                    $("#sqn").append(data.sqn.sqn)
                }else{
                    $("#sqn").append('--')
                }
               if(data.yield){
                $("#yield").append(data.yield+'<span>%</span>')
               }else{
                $("#yield").append('--')
               }
                if(data.pnl||data.pnl=='0'){
                    $("#pnl").append(toThousands(data.pnl))
                }else{
                    $("#pnl").append('--')
                }
               
                if(data.sharpeRatio.sharperatio==null){
                    $("#sharperatio").append('--')
                }else{
                    $("#sharperatio").append(data.sharpeRatio.sharperatio)
                }   
                if(data.portvalue){
                    $("#portvalue").append(data.portvalue)
                }else{
                    $("#portvalue").append('--')
                }
               if(data.cashvalue){
                $("#cashvalue").append(data.cashvalue.toFixed(2)) 
               }else{
                $("#cashvalue").append('--') 
               }
                if(data.drawDown&&data.drawDown.max){
                    $("#maxDrawdown").append(data.drawDown.max.drawdown.toFixed(2)+'<span>%</span>')
                    $("#maxMoneydown").append(data.drawDown.max.moneydown)
                    $("#maxLen").append(data.drawDown.max.len)
                }else{
                    $("#maxDrawdown").append('--')
                    $("#maxMoneydown").append('--')
                    $("#maxLen").append('--')
                }
                if(tradeAnalyzer.long){
                    $("#trades").append(tradeAnalyzer.long.total)
                    $('#lostLongest').append(tradeAnalyzer.long.lost)
                    $('#wonLongest').append(tradeAnalyzer.long.won)
                }else{
                    $("#trades").append('--')
                    $('#lostLongest').append('--')
                    $('#wonLongest').append('--')
                }
                
                console.log(data.timeReturn)
                timeReturnList=Object.entries(data.timeReturn)
                for(var i=0;i<timeReturnList.length;i++){
                    timeReturnList[i][0]= timeReturnList[i][0]-0
                }
                // document.write(a)
                timeReturnList.sort(function(x,y){
                    return x[0]-y[0]
                })
                Highcharts.setOptions({
		lang: {
			noData: '暂无数据'
		}
	});
                var chart = Highcharts.stockChart('container', {
                 
            chart: {
                zoomType:'xy',
                
               
        },
        exporting: {
            enabled: false
        },
        navigator : {
            height:50,
            margin:15,
			enabled : true
		},
        plotOptions: {
            series: {
                animation: {
                    duration: 2000
                },
            }
        },
    legend: {
        enabled: true,
        align: 'left',
        backgroundColor: '#ffffff',   
        layout: 'horizontal',
        verticalAlign: 'top',
        y: 33,
        x:0,
        itemMarginTop:0,
        floating: true,
        shadow: false,
        itemStyle:{"color": "#333333", "cursor": "pointer", "fontSize": "13px",'backgroundColor':null},
        
    },
    xAxis: {
        tickLength: 5,
    dateTimeLabelFormats: {
        year: '%Y',
        month: '%Y-%m',
        dat: '%Y-%m-%d',
        // ...
        // 当然还可以通过xAxis.labels.formatter 函数来格式化
    },
       labels: {        //设置X轴各分类名称的样式style
        formatter: function() { 
              var vDate=new Date(this.value); 
              return vDate.getFullYear()+"-"+(vDate.getMonth()+1)+"-"+vDate.getDate(); 

           }}     //定义x轴上数据显示格式（此处以日期格式为例）
} ,
    //版权信息
    credits: {
        enabled: false
    },
    scrollbar: {
      enabled: false
    },
    rangeSelector: {
        // selected: 3,
        // inputEnabled: false // 不显示日期输入框
    },
        tooltip: {
			formatter: function () {
                var vDate=new Date(this.x); 
				var s = '<b>' + vDate.getFullYear()+"-"+(vDate.getMonth()+1)+"-"+vDate.getDate() + '</b>';
				$.each(this.points, function () {
					s += '<br/><span style="color:'+this.series.color+'">' + this.series.name + '</span>: ' +
						this.y ;
				});
				return s;
			},
			shared: true
		},
    series: [{
        name: '策略收益率',
         color:'#b39258',
          type: 'areaspline',
          fillOpacity: 0.1,
        data: timeReturnList
    },
  
 ],
 noData: {
			style: {
				fontWeight: 'bold',
				fontSize: '15px',
				color: '#303030'
			}
		}
});
                $.ajax({
               type:"get",    //请求方式
               async:true,    //是否异步
            //    url:"http://192.168.80.196:8003/api/monitor-server/time/return",
               url:"/api/monitor-server/time/return",
               dataType :'JSON',
               headers: headers,
                 //jsonpCallback:"successCallback",    //自定义跨域参数值，回调函数名也是一样，默认为jQuery自动生成的字符串
             data:{
                 code:'SH.000300',
                 startDay:String(timeReturnList[0][0]).substr(0,10),
                 endDay:String(timeReturnList[timeReturnList.length-1][0]).substr(0,10),
             },
             success:function(data){    
                timeReturnList2=Object.entries(data.data)
                for(var i=0;i<timeReturnList2.length;i++){
                    timeReturnList2[i][0]= timeReturnList2[i][0]-0
                }
                // document.write(a)
                timeReturnList2.sort(function(x,y){
                    return x[0]-y[0]
                })
       
             }
                })
   
                recordsList = data.transactionRecordVO
                if(!recordsList){
                    $(".xiangqing1").css('display','none')
                }
                let array = []
                for (let i in recordsList) {
                    for(let j in recordsList[i].records){
                       
                        let item=recordsList[i].records[j]
                        var cny
                        var cns //币种
                        if(item.stockCode&&item.stockCode.split('.')[0]=='SZ'||item.stockCode&&item.stockCode.split('.')[0]=='SH'){
                            cny='CNY'
                            cns='￥'
                        }else if(item.stockCode&&item.stockCode.split('.')[0]=='HK'){
                            cny='HKD'
                            cns='HK$'
                        }else if(item.stockCode&&item.stockCode.split('.')[0]=='US'){
                            cny='USD'
                            cns='$'
                        }else if(item.stockCode&&item.stockCode.split('.')[0]=='JP'){
                            cny='JPY'
                            cns='￥'
                        }else{
                            cny='USD'
                            cns='$'
                        }
                        var profit//盈亏金额
                        if(item.profit==0){
                            profit='--'
                        }else{
                            profit=cns+toThousands(item.profit)
                        }
                        var profitRate//盈亏比例
                        if(item.profitRate==0){
                            profitRate='--'
                        }else{
                            profitRate=item.profitRate+'%'
                        }
                        if(item.type==0){ 
                            //买入股票
                            if(!item.stockName){
                                var divs='<ul><li class="li1"><span>'+ts(recordsList[i].date/1000*1000).split('.')[0]+'</span><br><span>'+ts(recordsList[i].date/1000*1000).split('.')[1]+'-'+ts(recordsList[i].date/1000*1000).split('.')[2]+'</span></li><li class="li2">买入</li><li class="li3"><span>****</span><br><span>****</span></li><li class="li4"><span>****</span><br><span>****</span></li><li class="li5"><span>****</span><br><span>****</span></li><li class="li6"><span>****</span><br><span>****</span></li></ul>'
                            }else{
                                var divs='<ul><li class="li1"><span>'+ts(recordsList[i].date/1000*1000).split('.')[0]+'</span><br><span>'+ts(recordsList[i].date/1000*1000).split('.')[1]+'-'+ts(recordsList[i].date/1000*1000).split('.')[2]+'</span></li><li class="li2">买入</li><li class="li3"><span>'+item.stockName+'</span><br><span class="stockCode">'+item.stockCode.slice(3,9)+'</span><span class="stockCodes" style="display:none">'+item.stockCode+'</span></li><li class="li4"><span>'+item.price+'</span><br><span>'+cny+'</span></li><li class="li5"><span>'+cns+toThousands(Math.abs(item.turnover))+'</span><br><span>'+Math.abs(item.volume)+'股</span></li><li class="li6"><span>'+profit+'</span><br/><span>'+profitRate+'</span></li></ul>'
                            }
                          
                        }else{
                            if(!item.stockName){
                                var divs='<ul><li class="li1"><span>'+ts(recordsList[i].date/1000*1000).split('.')[0]+'</span><br><span>'+ts(recordsList[i].date/1000*1000).split('.')[1]+'-'+ts(recordsList[i].date/1000*1000).split('.')[2]+'</span></li><li class="li2">卖出</li><li class="li3"><span>****</span><br><span>****</span></li><li class="li4"><span>****</span><br><span>****</span></li><li class="li5"><span>****</span><br><span>****</span></li><li class="li6"><span>****</span><br><span>****</span></li></ul>'
                            }else{
                                var divs='<ul><li class="li1"><span>'+ts(recordsList[i].date/1000*1000).split('.')[0]+'</span><br><span>'+ts(recordsList[i].date/1000*1000).split('.')[1]+'-'+ts(recordsList[i].date/1000*1000).split('.')[2]+'</span></li><li class="li2">卖出</li><li class="li3"><span>'+item.stockName+'</span><br><span class="stockCode">'+item.stockCode.slice(3,9)+'</span><span class="stockCodes" style="display:none">'+item.stockCode+'</span></li><li class="li4"><span>'+item.price+'</span><br><span>'+cny+'</span></li><li class="li5"><span>'+cns+toThousands(Math.abs(item.turnover))+'</span><br><span>'+Math.abs(item.volume)+'股</span></li><li class="li6"><span>'+profit+'</span><br/><span>'+profitRate+'</span></li></ul>'
                            }
                          
                        }

                        $(".xiangqing2").append(divs)
                       
                    }
                }
            

                
             },
            })
     
    </script>
</body>
</html>